package biz.yfsoft.app.fastframework.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 用于操作用户信息
 * @author James
 *
 */
@ClearInterceptor
public class UserController extends Controller{
	
	public DbPro db = Db.use("biz"); 
	
	public DbPro ecDb = Db.use("ec");
	
	/**
	 * 用户注册
	 * @param login_name login_pass cfg_pass
	 * @author james 2016-03-02
	 */
	@Before(Tx.class)
	public void signup(){
		
		String login_name = getPara("login_name");						//登录账号
		String type = getPara("type");									//登录类型 1：手机号 2:邮箱  3:微信 4:qq 5:登录名
		String login_pass = getPara("login_pass");						//密码
		String cfg_pass = getPara("cfg_pass");							//确认密码

		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", "normal");
		o.put("msg", "运行正常");
		
		if(StringUtils.isEmpty(login_name)){
			o.put("errno", -601);
			o.put("code", "LOGINNAME CANT BE EMPTY");
			o.put("msg", "登录名不能为空");
		}else if(StringUtils.isEmpty(type)){
			o.put("errno", -602);
			o.put("code", "LOGINTYPE CANT BE EMPTY");
			o.put("msg", "登录类型不能为空");
		}else if(!"1".equals(type) && !"2".equals(type) && !"3".equals(type) && !"4".equals(type) && !"5".equals(type)){
			o.put("errno", -603);
			o.put("code", "LOGINTYPE ABNORMAL VALUE");
			o.put("msg", "登录类型值异常");
		}else if(!"3".equals(type) && !"4".equals(type) && StringUtils.isEmpty(login_pass)){
			o.put("errno", -604);
			o.put("code", "LOGINPASS CANT BE EMPTY");
			o.put("msg", "密码不能为空");
			setAttr("login_name", login_name);
		}else if(!"3".equals(type) && !"4".equals(type) && login_pass.length()<6){
			o.put("errno", -605);
			o.put("code", "LOGINPASS LENGTH CANNOT BE LESS THAN 6");
			o.put("msg", "密码长度不少于6位");
			setAttr("login_name", login_name);
		}else if(!"3".equals(type) && !"4".equals(type) && !login_pass.equals(cfg_pass)){
			o.put("errno", -606);
			o.put("code", "LOGINPASS IS NOT CONSISTENT");
			o.put("msg", "密码不一致");
			setAttr("login_name", login_name);
		}else{
			String sql = "select a.id from gr_login_info a";
			if("1".equals(type)){
				sql += " where a.status = 1 and a.phone = '"+login_name+"'";
			}else if("2".equals(type)){
				sql += " where a.status = 1 and a.email = '"+login_name+"'";
			}else if("3".equals(type)){
				sql += ",gr_thirdparty b where a.status = 1 and a.id = b.uid and b.openidType = 'WX' and b.openid = '"+login_name+"'";
			}else if("4".equals(type)){
				sql += ",gr_thirdparty b where a.status = 1 and a.id = b.uid and b.openidType = 'QQ' and b.openid = '"+login_name+"'";
			}else if("5".equals(type)){
				sql += " where a.status = 1 and a.login_name = '"+login_name+"'";
			} 
			
			List<Record> users = db.find(sql);
			if(users.size() > 0){
				o.put("errno", -607);
				o.put("code", "LOGINNAME CANNOT BE REPEATED REGISTRATION");
				o.put("msg", "用户名不可重复注册");
			}else{
				Record gr_login_info = new Record();
				String openidType = "";
				if("1".equals(type)){
					gr_login_info.set("phone", login_name);
				}else if("2".equals(type)){
					gr_login_info.set("email", login_name);
				}else if("3".equals(type)){
					openidType = "WX";
				}else if("4".equals(type)){
					openidType = "QQ";
				}else if("5".equals(type)){
					gr_login_info.set("login_name", login_name);
				}
				
				gr_login_info.set("login_pass", login_pass);
				gr_login_info.set("level", 2);
				gr_login_info.set("point", 0);
				gr_login_info.set("balance", 0);
				gr_login_info.set("status", 1);
				gr_login_info.set("createAt", System.currentTimeMillis());
				gr_login_info.set("updateAt", System.currentTimeMillis());
				boolean flag = db.save("gr_login_info", gr_login_info);

				if(!flag){
					o.put("errno", -608);
					o.put("code", "Network anomaly");
					o.put("msg", "网络异常，请稍候再试");
				}else{
					if("3".equals(type) || "4".equals(type)){
						Record gr_thirdparty = new Record();
						gr_thirdparty.set("uid", Integer.parseInt(gr_login_info.get("id").toString()));
						gr_thirdparty.set("openid", login_name);
						gr_thirdparty.set("openidType", openidType);
						db.save("gr_thirdparty", gr_thirdparty);
					}
					Map<String,Object> p = new HashMap<String,Object>();
					p.put("login_name", login_name);
					o.put("data", p);
				}
			}
		}
		renderJson(o);
	}
	
	/**
	 * 用户登录
	 * @param  login_name login_pass
	 * @author james 2016-03-02
	 */
	public void signin(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", "normal");
		o.put("msg", "运行正常");
		
		String login_name = getPara("login_name");
		String login_pass = getPara("login_pass");	
		String type = getPara("type");									//登录类型 1：手机号 2:邮箱  3:微信 4:qq 5:登录名
		
		if(StringUtils.isEmpty(login_name)){
			o.put("errno", -601);
			o.put("code", "LOGINNAME CANT BE EMPTY");
			o.put("msg", "登录名不能为空");
		}else if(StringUtils.isEmpty(type)){
			o.put("errno", -602);
			o.put("code", "LOGINTYPE CANT BE EMPTY");
			o.put("msg", "登录类型不能为空");
		}else if(!"1".equals(type) && !"2".equals(type) && !"3".equals(type) && !"4".equals(type) && !"5".equals(type)){
			o.put("errno", -603);
			o.put("code", "LOGINTYPE ABNORMAL VALUE");
			o.put("msg", "登录类型值异常");
		}else if(!"3".equals(type) && !"4".equals(type) && StringUtils.isEmpty(login_pass)){
			o.put("errno", -604);
			o.put("code", "LOGINPASS CANT BE EMPTY");
			o.put("msg", "密码不能为空");
			setAttr("login_name", login_name);
		}else{
			String sql = "select a.id,a.balance,a.point,a.nickname,a.level,a.lastlogintime,a.headimgurl,b.openid,a.objectId from gr_login_info a";
			if("1".equals(type)){
				sql += " where a.status = 1 and a.phone = '"+login_name+"' and a.login_pass = '"+login_pass+"'";
			}else if("2".equals(type)){
				sql += " where a.status = 1 and a.email = '"+login_name+"' and a.login_pass = '"+login_pass+"'";
			}else if("3".equals(type)){
				sql += ",gr_thirdparty b where a.status = 1 and a.id = b.uid and b.openidType = 'WX' and b.openid = '"+login_name+"'";
			}else if("4".equals(type)){
				sql += ",gr_thirdparty b where a.status = 1 and a.id = b.uid and b.openidType = 'QQ' and b.openid = '"+login_name+"'";
			}else if("5".equals(type)){
				sql += " where a.status = 1 and a.login_name = '"+login_name+"' and a.login_pass = '"+login_pass+"'";
			} 
			
			List<Record> users = db.find(sql);
			if(users.size() == 0){
				o.put("errno", -609);
				o.put("code", "Username or password is wrong");
				o.put("msg", "用户名或密码有误");
				setAttr("login_name", login_name);
			}else{
				users.get(0).set("login_name", login_name);
				o.put("data", users.get(0));
			}
		}

		renderJson(o);
	}
	
	/**
	 * 用户登出
	 * @param  login_name
	 * @author james 2016-03-02
	 */
	public void signout(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", "normal");
		o.put("msg", "运行正常");
		
		String login_name = getPara("login_name");
		String type = getPara("type");									//登录类型 1：手机号 2:邮箱  3:微信 4:qq 5:登录名
		
		if(StringUtils.isEmpty(login_name)){
			o.put("errno", -601);
			o.put("code", "LOGINNAME CANT BE EMPTY");
			o.put("msg", "登录名不能为空");
		}else if(StringUtils.isEmpty(type)){
			o.put("errno", -602);
			o.put("code", "LOGINTYPE CANT BE EMPTY");
			o.put("msg", "登录类型不能为空");
		}else if(!"1".equals(type) && !"2".equals(type) && !"3".equals(type) && !"4".equals(type) && !"5".equals(type)){
			o.put("errno", -603);
			o.put("code", "LOGINTYPE ABNORMAL VALUE");
			o.put("msg", "登录类型值异常");
		}

		renderJson(o);
	}
	
	/**
	 * 新增用户积分
	 * @param uid points
	 * 先插入用户积分流水表，再更新用户表上的实时积分
	 * @author james 2016-02-28
	 */
	@Before(Tx.class)
	public void addUserPoints(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", 0);
		o.put("msg", "运行正常");
		
		String uid = getPara("uid");			//用户编号
		String points = getPara("points");		//需要增加的积分
		String content = getPara("content");	//详情			
		
		if(StringUtils.isEmpty(uid)){
			o.put("errno", -601);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "参数uid不能为空");
		}else if(StringUtils.isEmpty(points)){
			o.put("errno", -602);
			o.put("code", "POINTS CANT BE EMPTY");
			o.put("msg", "参数points不能为空");
		}else if(isNumeric(points)==false){
			o.put("errno", -603);
			o.put("code", "POINTS MUST BE INT");
			o.put("msg", "参数points只能为数字");
		}else if(StringUtils.isEmpty(content)){
			o.put("errno", -604);
			o.put("code", "CONTENT CANT BE EMPTY");
			o.put("msg", "参数content不能为空");
		}else{
			Record record = new Record();
			
			String fsql = "select ifnull(point,0) point from wyl_user where objectId = '"+uid+"' ";
			List<Record> users = db.find(fsql);
			
			if(users.size() == 0){
				o.put("errno", -605);
				o.put("code", "CANT FOUND USER");
				o.put("msg", "参数uid未找到用户");
			}else{
				String beforepoint = users.get(0).get("point").toString();
				int afterpoint = Integer.parseInt(beforepoint) + Integer.parseInt(points); 
				
				record.set("uid", uid);
				record.set("newpoint", Integer.parseInt(points));
				record.set("beforepoint", Integer.parseInt(beforepoint));
				record.set("afterpoint", afterpoint);
				record.set("content", content);
				record.set("status", 1);
				record.set("createAt", System.currentTimeMillis());
				record.set("updateAt", System.currentTimeMillis());
				
				//插入到积分流水表中
				db.save("wyl_pointflow", record);
				
				//更新用户表的实时积分
				db.update("update wyl_user set point = ? where objectId = ?",afterpoint,uid);
			}
		}
		
		renderJson(o);
	}
	
	/**
	 * 减少用户积分
	 * @param uid points
	 * 先插入用户积分流水表，再更新用户表上的实时积分
	 * @author james 2016-03-01
	 */
	@Before(Tx.class)
	public void lessenUserPoints(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", 0);
		o.put("msg", "运行正常");
		
		String uid = getPara("uid");			//用户编号
		String points = getPara("points");		//需要增加的积分
		String content = getPara("content");	//详情			
		
		if(StringUtils.isEmpty(uid)){
			o.put("errno", -601);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "参数uid不能为空");
		}else if(StringUtils.isEmpty(points)){
			o.put("errno", -602);
			o.put("code", "POINTS CANT BE EMPTY");
			o.put("msg", "参数points不能为空");
		}else if(isNumeric(points)==false){
			o.put("errno", -603);
			o.put("code", "POINTS MUST BE INT");
			o.put("msg", "参数points只能为数字");
		}else if(StringUtils.isEmpty(content)){
			o.put("errno", -604);
			o.put("code", "CONTENT CANT BE EMPTY");
			o.put("msg", "参数content不能为空");
		}else{
			Record record = new Record();
			
			String fsql = "select ifnull(point,0) point from wyl_user where objectId = '"+uid+"' ";
			List<Record> users = db.find(fsql);
			
			if(users.size() == 0){
				o.put("errno", -605);
				o.put("code", "CANT FOUND USER");
				o.put("msg", "参数uid未找到用户");
			}else{
				String beforepoint = users.get(0).get("point").toString();
				int afterpoint = Integer.parseInt(beforepoint) - Integer.parseInt(points); 
				
				record.set("uid", uid);
				record.set("newpoint", Integer.parseInt(points));
				record.set("beforepoint", Integer.parseInt(beforepoint));
				record.set("afterpoint", afterpoint);
				record.set("content", content);
				record.set("status", 1);
				record.set("createAt", System.currentTimeMillis());
				record.set("updateAt", System.currentTimeMillis());
				
				//插入到积分流水表中
				db.save("wyl_pointflow", record);
				
				//更新用户表的实时积分
				db.update("update wyl_user set point = ? where objectId = ?",afterpoint,uid);
			}
		}
		
		renderJson(o);
	}
	
	/**
	 * 新增用户余额
	 * @param uid points
	 * 先插入用户余额流水表，再更新用户表上的实时余额
	 * @author james 2016-03-01
	 */
	@Before(Tx.class)
	public void addUserBalance(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", 0);
		o.put("msg", "运行正常");
		
		String uid = getPara("uid");			//用户编号
		String balance = getPara("balance");		//需要增加的余额
		String content = getPara("content");	//详情			
		
		if(StringUtils.isEmpty(uid)){
			o.put("errno", -601);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "参数uid不能为空");
		}else if(StringUtils.isEmpty(balance)){
			o.put("errno", -606);
			o.put("code", "BALANCE CANT BE EMPTY");
			o.put("msg", "参数balance不能为空");
		}else if(isNumeric(balance)==false){
			o.put("errno", -607);
			o.put("code", "BALANCE MUST BE INT");
			o.put("msg", "参数balance只能为数字");
		}else if(StringUtils.isEmpty(content)){
			o.put("errno", -604);
			o.put("code", "CONTENT CANT BE EMPTY");
			o.put("msg", "参数content不能为空");
		}else{
			Record record = new Record();
			
			String fsql = "select ifnull(amount,0) balance from wyl_user where objectId = '"+uid+"' ";
			List<Record> users = db.find(fsql);
			
			if(users.size() == 0){
				o.put("errno", -605);
				o.put("code", "CANT FOUND USER");
				o.put("msg", "参数uid未找到用户");
			}else{
				String beforebalance = users.get(0).get("balance").toString();
				int afterbalance = Integer.parseInt(beforebalance) + Integer.parseInt(balance); 
				
				record.set("uid", uid);
				record.set("newpoint", Integer.parseInt(balance));
				record.set("beforepoint", Integer.parseInt(beforebalance));
				record.set("afterpoint", afterbalance);
				record.set("content", content);
				record.set("status", 1);
				record.set("createAt", System.currentTimeMillis());
				record.set("updateAt", System.currentTimeMillis());
				
				db.save("wyl_pointflow", record);
				
				//更新用户表的实时积分
				db.update("update wyl_user set amount = ? where objectId = ?",afterbalance,uid);
			}
		}
		
		renderJson(o);
	}
	
	/**
	 * 减少用户余额
	 * @param uid balance
	 * 先插入用户余额流水表，再更新用户表上的实时余额
	 * @author james 2016-03-01
	 */
	@Before(Tx.class)
	public void lessenUserBalance(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", 0);
		o.put("msg", "运行正常");
		
		String uid = getPara("uid");			//用户编号
		String balance = getPara("balance");		//需要增加的积分
		String content = getPara("content");	//详情			
		
		if(StringUtils.isEmpty(uid)){
			o.put("errno", -601);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "参数uid不能为空");
		}else if(StringUtils.isEmpty(balance)){
			o.put("errno", -606);
			o.put("code", "BALANCE CANT BE EMPTY");
			o.put("msg", "参数balance不能为空");
		}else if(isNumeric(balance)==false){
			o.put("errno", -607);
			o.put("code", "BALANCE MUST BE INT");
			o.put("msg", "参数balance只能为数字");
		}else if(StringUtils.isEmpty(content)){
			o.put("errno", -604);
			o.put("code", "CONTENT CANT BE EMPTY");
			o.put("msg", "参数content不能为空");
		}else{
			Record record = new Record();
			
			String fsql = "select ifnull(amount,0) balance from wyl_user where objectId = '"+uid+"' ";
			List<Record> users = db.find(fsql);
			
			if(users.size() == 0){
				o.put("errno", -605);
				o.put("code", "CANT FOUND USER");
				o.put("msg", "参数uid未找到用户");
			}else{
				String beforebalance = users.get(0).get("balance").toString();
				int afterbalance = Integer.parseInt(beforebalance) - Integer.parseInt(balance); 
				
				record.set("uid", uid);
				record.set("newbalance", Integer.parseInt(balance));
				record.set("beforebalance", Integer.parseInt(beforebalance));
				record.set("afterbalance", afterbalance);
				record.set("content", content);
				record.set("status", 1);
				record.set("createAt", System.currentTimeMillis());
				record.set("updateAt", System.currentTimeMillis());
				
				db.save("wyl_amountflow", record);
				
				//更新用户表的实时积分
				db.update("update wyl_user set amount = ? where objectId = ?",afterbalance,uid);
			}
		}
		
		renderJson(o);
	}
	
	/**
	 * 获取用户基本信息
	 * @param uid
	 * @author james 2016-03-01
	 */
	public void getUser(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", 0);
		o.put("msg", "运行正常");
		
		String uid = getPara("uid");			//用户编号		
		
		if(StringUtils.isEmpty(uid)){
			o.put("errno", -601);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "参数uid不能为空");
		}else{
			String fsql = "select * from wyl_user where objectId = '"+uid+"' ";
			List<Record> users = db.find(fsql);
			
			if(users.size() == 0){
				o.put("errno", -605);
				o.put("code", "CANT FOUND USER");
				o.put("msg", "参数uid未找到用户");
			}else{
				o.put("detail", users);
			}
		}
		
		renderJson(o);
	}
	
	/**
	 * 获取用户积分流水记录
	 * @param uid
	 * @author james 2016-03-01
	 */
	public void getPointsFlow(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", 0);
		o.put("msg", "运行正常");
		
		String uid = getPara("uid");			//用户编号		
		
		if(StringUtils.isEmpty(uid)){
			o.put("errno", -601);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "参数uid不能为空");
		}else{
			String fsql = "select * from wyl_user where objectId = '"+uid+"' ";
			List<Record> users = db.find(fsql);
			o.put("detail", users);
		}
		
		renderJson(o);
	}
	
	/**
	 * 获取用户余额流水记录
	 * @param uid
	 * @author james 2016-03-01
	 */
	public void getBalanceFlow(){
		
		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", 0);
		o.put("msg", "运行正常");
		
		String uid = getPara("uid");			//用户编号		
		
		if(StringUtils.isEmpty(uid)){
			o.put("errno", -601);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "参数uid不能为空");
		}else{
			String fsql = "select * from wyl_user where objectId = '"+uid+"' ";
			List<Record> users = db.find(fsql);
			o.put("detail", users);
		}
		
		renderJson(o);
	}
	
	/**
	 * 判断是否数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str){ 
	    Pattern pattern = Pattern.compile("[0-9]*"); 
	    return pattern.matcher(str).matches();    
	 } 
}
